import Markdown, { RuleType } from "markdown-to-jsx";
import { useMemo } from "react";

type MarkdownMessageProps = {
  markdown: string;
  onClickSourceCitation: (index: number) => void;
};

export default function MarkdownMessage(props: MarkdownMessageProps) {
  const { markdown, onClickSourceCitation } = props;
  const parsed = useMemo(() => {
    return markdown.replaceAll(/\[citation:(\d+)\]/g, (m, $1) => {
      return `<SourceCitation data-index="${$1}" />`;
    });
  }, [markdown]);

  return (
    <Markdown
      options={{
        renderRule(next, node, renderChildren, state) {
          if (
            node.type === RuleType.htmlSelfClosing &&
            node.tag === "SourceCitation"
          ) {
            const index = (node.attrs as Record<string, string>)["data-index"];
            return (
              <SourceCitation
                key={index}
                onClick={onClickSourceCitation}
                index={index}
              />
            );
          }
          return next();
        },
      }}
    >
      {parsed}
    </Markdown>
  );
}

type SourceCitationProps = {
  index: string;
  onClick: (index: number) => void;
};
function SourceCitation(props: SourceCitationProps) {
  const { index, onClick } = props;

  return (
    <sup
      onClick={() => onClick(parseInt(index))}
      className="mx-px inline-block size-3.5 cursor-pointer rounded-full border text-center leading-none"
    >
      {index}
    </sup>
  );
}
